package pl.diagnoser.server;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private File tmpDir;

	@Override
	  public void doGet(HttpServletRequest request, HttpServletResponse response)
	      throws ServletException, IOException {
	    this.process(request, response);
	  }

	  @Override
	  public void doPost(HttpServletRequest request, HttpServletResponse response)
	      throws ServletException, IOException {
	    this.process(request, response);
	  }
	  
	  private void process(HttpServletRequest request, HttpServletResponse response)
		      throws ServletException, IOException {
		  if (ServletFileUpload.isMultipartContent(request)) {
			  processFiles(request, response);
		  }
	  }
	  
	  private void processFiles(HttpServletRequest request, HttpServletResponse response)
		      throws ServletException, IOException {
		  
		  
		  String DESTINATION_DIR_PATH = getServletContext().getRealPath("/") + "articles";
		  System.out.println("ŚCIEZKA: " + DESTINATION_DIR_PATH);
		  DiskFileItemFactory factory = new DiskFileItemFactory();
		  factory.setRepository(tmpDir);

		  ServletFileUpload upload = new ServletFileUpload(factory);

		  try {
		      @SuppressWarnings("unchecked")
		      List<FileItem> items = upload.parseRequest(request);
		      for (FileItem item : items) {
		    	  if (item.isFormField())
		    		  continue;
		    	  
		    	  String fileName = item.getName();
		    	  if (fileName != null) {
		    		  fileName = FilenameUtils.getName(fileName);
		    	  }
		    	  
		    	  File uploadedFile = new File(DESTINATION_DIR_PATH, fileName);
		    	  if (uploadedFile.createNewFile()) {
		    		  item.write(uploadedFile);
		    		  response.setStatus(HttpServletResponse.SC_CREATED);
		    		  response.getWriter().print("The file was created successfully.");
		    		  response.flushBuffer();
		    	  } else
		    		  throw new IOException("The file already exists in repository.");
		    		 
		      }  
		  } catch (Exception e) {
    		  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
    				  		      "An error occurred while creating the file : "
    				  		      + e.getMessage());
    	  }
    	  
	  }
}